const qiniu = require('qiniu')
const nanoid = require('nanoid')
const config = require('../config')

const bucket = config.qiniu.bucket
const mac = new qiniu.auth.digest.Mac(config.qiniu.AK, config.qiniu.SK)
const cfg = new qiniu.conf.Config()
const client = new qiniu.rs.BucketManager(mac, cfg)

const uploadToQiniu = async (url, key) => {
    return new Promise((resolve, reject) => {
        client.fetch(url, bucket, key, (err, ret, info) => {
            if (err) {
                console.log('chucuole')
                reject(err)
            } else {
                if (info.statusCode === 200) {
                    resolve({ key })
                } else {
                    reject(info)
                }
            }
        })
    })
}

;(async () => {
    let movies = [{
        doubanId: 26683290,
        poster:'https://img1.doubanio.com/view/photo/l_ratio_poster/public/p2395733377.jpg',
        video: 'http://vt1.doubanio.com/201908151018/dc6bf9029b8b2a9504e43a8810f413db/view/movie/M/302080103.mp4',
        cover: 'https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2395733377.jpg'
    }]
    movies.map(async movie => {
        if (movie.video && !movie.key) {
            try {

                let videoData = await uploadToQiniu(movie.video, nanoid() + '.mp4')

                let coverData = await uploadToQiniu(movie.cover, nanoid() + '.png')

                let posterData = await uploadToQiniu(movie.poster, nanoid() + '.png')
                if (videoData.key) {
                    movie.videoKey = videoData.key
                }
                if (coverData.key) {
                    movie.coverKey = coverData.key
                }
                if (posterData.key) {
                    movie.posterKey = posterData.key
                }
                console.log(movie)
            } catch (e) {
                console.log(e)
            }
        }
    })
})()